package com.wodwl.dao;

import java.io.IOException;

import java.io.Reader;

import java.util.List;

import org.apache.commons.digester.xmlrules.FromXmlRuleSet;

import com.ibatis.common.resources.Resources;

import com.ibatis.sqlmap.client.SqlMapClient;

import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.wodwl.entity.Post;

public class PostDao {

	public static enum Mode {

		INSERT, UPDATE, DELETE

	}
	public void update(Object arg, Mode mode) {

		SqlMapClient smc = null;

		try {

			smc = getSqlMapClient();
			smc.startTransaction();

			switch (mode) {

			case INSERT:
				smc.insert("post.insertPost", arg);
				break;

			case UPDATE:
				smc.update("post.updatePostByPid", arg);
				break;

			case DELETE:
				smc.delete("post.deletePost", arg);
				break;

			}

			smc.commitTransaction();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			endTransaction(smc);
		}
	}
	
	public List<Post> getAllPostsByPath(int fid) {
		SqlMapClient smc = null;
		List<Post> posts=null;
		try {
			smc = getSqlMapClient();
			smc.startTransaction();
			posts =(List<Post>) smc.queryForList("post.getPostsByPath", fid);
			smc.commitTransaction();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			endTransaction(smc);
		}
		return posts;

	}

	public Post getPostByPid(int fid) {
		Post post = null;
		SqlMapClient smc = null;
		try {
			smc = getSqlMapClient();
			smc.startTransaction();
			post = (Post) smc.queryForObject("post.getPostByPid", fid);
			smc.commitTransaction();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			endTransaction(smc);

		}
		return post;

	}

	// //
	// ////////////////////////////////////////////////////////////////////////

	private SqlMapClient getSqlMapClient() throws IOException {

		// 初始化ibatis, 获得一个SqlMapClient对象

		String resource = "ibatis/SqlMapConfig.xml";
		Reader reader = Resources.getResourceAsReader(resource);
		return SqlMapClientBuilder.buildSqlMapClient(reader);

	}

	private void endTransaction(SqlMapClient smc) {

		if (smc == null) {
			return;
		}
		try {
			smc.endTransaction();
		} catch (Exception e2) {
			e2.printStackTrace();
		}

	}

	public static void main(String[] args) {
		PostDao dao = new PostDao();
		Post post=new Post();
		
		
		 //增
		post.setContent("hello world");
		post.setFrom_user("bbb");
		post.setTo_user("aaa");
		dao.update(post, Mode.INSERT);
		
		
		
		//查
		post=dao.getPostByPid(16);
		System.out.println(post.getContent());
		
		
		
		//改
		post.setPid(16);
		post.setContent("update");
		dao.update(post, Mode.UPDATE);
		
		
		
		//删
		dao.update(17, Mode.DELETE);
		
		List<Post> list=dao.getAllPostsByPath(2);
		System.out.println(list.size());
		
		
	}

}